package _09_高频题;

import java.util.HashMap;

/**
 * https://leetcode-cn.com/problems/two-sum/
 * @Author: haogege
 * @Date: 2021/9/1
 */

public class _1_两数之和 {

    // 小于n^2时间复杂度
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(nums[0], 0);
        // 利用hash表，保存上一次访问的值
        for (int i = 1; i < nums.length; i++) {
            int remain = target - nums[i];
            Integer data = map.get(remain);
            if (data != null) {
                result[0] = data;
                result[1] = i;
                break;
            }
            // 存入当前值
            map.put(nums[i], i);
        }
        return result;
    }

    // n^2时间复杂度
    public int[] twoSum1(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int first = nums[i];
            if (result[1] != 0) break;
            for (int j = i - 1; j < nums.length; j++) {
                if (first + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    break;
                }
            }
        }
        return result;
    }

}
